from email.mime.text import MIMEText
from email.utils import formataddr
from config.settings import get_settings
from get_logger import get_server_logger, get_error_logger
import smtplib
import threading
import time
import sched


server_logger = get_server_logger()
error_logger = get_error_logger()

settings = get_settings()

__all__ = [
    'thread_pool_send_email',
]

daily_email_count = 0
scheduler = sched.scheduler(time.time, time.sleep)

# 每天重置计数器的函数
def reset_daily_email_count():
    global daily_email_count
    daily_email_count = 0
    print("邮件发送计数已重置。")


def thread_pool_send_email(recipient_email, subject, message):
    """
    Args:
        recipient_email (_type_): 收件人
        subject (_type_): 标题
        message (_type_): 内容
    """
    global daily_email_count
    if daily_email_count >= 20:
        print("已达到每日发送限制，无法发送更多邮件。")
        return

    email_thread = threading.Thread(
        target=send_email, args=(recipient_email, subject, message,))
    email_thread.start()

    daily_email_count += 1
    # 如果是第一封邮件，安排每天定时重置计数器
    if daily_email_count == 1:
        tomorrow = time.mktime((time.localtime().tm_year, time.localtime().tm_mon, time.localtime().tm_mday + 1, 0, 0, 0, 0, 0, -1))
        scheduler.enterabs(tomorrow, 1, reset_daily_email_count, ())


def send_email(recipient_email, subject, message):
    """
    Args:
        recipient_email (_type_): 收件人
        subject (_type_): 标题
        message (_type_): 内容
    """
    from_addr = formataddr(("PHD-LOCO", settings.SERVER_EMAIL))
    to_addr = recipient_email

    msg = MIMEText(message, 'html')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = subject

    try:
        server = smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT)
        server.starttls()
        server.ehlo()
        server.login(settings.SERVER_EMAIL, settings.EMAIL_PASSWORD)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server_logger.info('Email sent successfully')
    except Exception as e:
        print('Email sending failed', str(e))
        error_logger.error(f'Email sending failed: [{str(e)}]')
    finally:
        if server:
            server.quit()
